package com.hpq.chat.dao;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hpq.chat.domain.enums.MessageStatusEnum;
import com.hpq.chat.domain.model.Message;
import com.hpq.chat.domain.vo.request.ChatMessagePageReq;
import com.hpq.chat.mapper.MessageMapper;
import com.hpq.chat.service.MessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hpq.common.domain.vo.response.CursorPageBaseResp;
import com.hpq.common.utils.CursorUtils;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.sql.Wrapper;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 消息表 服务实现类
 * </p>
 *
 * @author hpq
 * @since 2024-12-16
 */
@Service
public class MessageDAO extends ServiceImpl<MessageMapper, Message> {
    /**
     *  获取未读消息数量
     * @param roomId
     * @param fromId
     * @param toId
     * @return
     */
    public Integer getGapCount(Long roomId, Long fromId, Long toId) {
        return lambdaQuery()
                .eq(Message::getRoomId, roomId)
                .gt(Message::getId,fromId)
                .le(Message::getId,toId)
                .count();
    }

    public CursorPageBaseResp<Message> getCursorPage( Long roomId, ChatMessagePageReq req, Long lastMsgId) {
        return CursorUtils.getCursorPageByMysql(this,req, wrapper ->{
            wrapper.eq(Message::getRoomId, roomId)
                    .eq(Message::getFromUid, lastMsgId)
                    .eq(Message::getStatus, MessageStatusEnum.NORMAL.getStatus())
                    .le(Objects.nonNull(lastMsgId), Message::getId, lastMsgId);
        }, Message::getId);
    }
    public Integer getUnReadCount(Long roomId, Date readTime) {
        return lambdaQuery()
                .eq(Message::getRoomId, roomId)
                .gt(Objects.nonNull(readTime), Message::getCreateTime, readTime)
                .count();
    }

    public Boolean removeByRoomId(Long roomId, List<Long> uidList) {
        if (CollectionUtil.isNotEmpty(uidList)) {
            LambdaUpdateWrapper<Message> wrapper = new UpdateWrapper<Message>().lambda()
                    .eq(Message::getRoomId, roomId)
                    .in(Message::getFromUid, uidList)
                    .set(Message::getStatus, MessageStatusEnum.DELETE.getStatus());
            return this.update(wrapper);
        }
        return false;
    }
}
